<template>
  <el-card class="box-card">
    <div slot="header">
      <span>添加分类</span>
    </div>
    <el-form ref="ruleForm" v-loading.body="loading" :label-position="labelPosition" label-width="80px" :model="category" :rules="rules">
      <el-form-item label="分类名" prop="title">
        <el-input v-model="category.title" @keyup.enter.native="save" />
      </el-form-item>
      <el-form-item label="父类">
        <el-cascader v-model="treeValue" expand-trigger="click" :options="categoryTree" :change-on-select="true" :props="props" placeholder="顶级分类" clearable @change="handleItemChange" />
      </el-form-item>
      <el-form-item label="序号" prop="priority">
        <el-input v-model="category.priority" type="number" @keyup.enter.native="save" />
      </el-form-item>
      <el-form-item v-loading.body="avatarUploading" label="分类图">
        <el-upload action="api/file/upload" :data="tokenObject" :auto-upload="true" name="file" list-type="picture-card" :show-file-list="false" :on-success="avatarUploadSuccess" :before-upload="avatarBeforeUpload">
          <img v-if="category.avatarUrl" :src="category.avatarUrl" class="thumb">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item v-loading.body="bannerUploading" label="海报图">
        <el-upload action="api/file/upload" :data="tokenObject" :auto-upload="true" name="file" list-type="picture-card" :show-file-list="false" :on-success="bannerUploadSuccess" :before-upload="bannerBeforeUpload">
          <img v-if="category.bannerUrl" :src="category.bannerUrl" class="thumb">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save()">添加</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { save, detail, list } from '@/api/category'
export default {
  data() {
    return {
      msg: 'Login',
      isEdit: false,
      labelPosition: 'right',
      loading: false,
      category: {
        title: '',
        priority: '',
        pid: ''
      },
      tokenObject: { token: localStorage.getItem('token') },
      categoryTree: [], // 处理过后的tree
      treeValue: [],
      props: {
        // cascader props
        value: '_id',
        label: 'title',
        children: 'children'
      },
      avatarUploading: false, // 正在上传分类图
      bannerUploading: false, // 正在上传海报图
      rules: {
        title: [{
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }],
        priority: [{
          required: true,
          message: '请输入序号',
          trigger: 'blur'
        }]
      }
    }
  },
  created: function() {
    new Promise((resolve, reject) => {
      list().then(response => {
        var categoryObjects = response.data
        // 递归
        var { tree } = require('../../utils/utils')
        this.categoryTree = tree(categoryObjects, '')
        resolve(categoryObjects)
      })
    }).then(categoryObjects => {
      // 如果是编辑
      if (this.$route.query._id) {
        console.log(this.$route.query._id)
        this.isEdit = true
        // 加载商品数据
        detail({ _id: this.$route.query._id }).then(response => {
          console.log(response)
          this.category = response.data
          this.category.priority = this.category.priority.toString()
          // 还有找到一直向上推进的父类
          var { findAncestors } = require('../../utils/utils')
          var treeValue = findAncestors(categoryObjects, this.$route.query._id)
          this.treeValue = treeValue.reverse().slice(0, -1)
        })
      }
    })
  },
  methods: {
    handleItemChange: function(val) {
      this.category.pid = val.slice(-1)
    },
    avatarBeforeUpload: function() {
      this.avatarUploading = true
    },
    bannerBeforeUpload: function() {
      this.bannerUploading = true
    },
    avatarUploadSuccess: function(res) {
      // console.log(res);
      // 回调设定图片路径，下同
      this.category.avatarUrl = res.data.url
      // 关闭正在上传的动画
      this.avatarUploading = false
    },
    bannerUploadSuccess: function(res) {
      // console.log(res);
      this.category.bannerUrl = res.data.url
      this.bannerUploading = false
    },
    save: function() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true
          save(this.category).then(response => {
            // 输出服务端返回
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: response.msg,
                duration: 500,
                onClose: () => {
                  this.loading = false
                  // this.$router.push({ name: 'categoryList' });
                }
              })
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
              this.loading = false
            }
          }).finally(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
<style>
body {
    font-family: Helvetica, sans-serif;
}
</style>
